import {
    createSlice,
    configureStore
} from "@reduxjs/toolkit";
// 总结：可以通过store.dispatch来接收action,来调用reducer修改state
// 1- 创建slice
const counterSlice = createSlice({
    name:"counter",
    initialState:{
        num:0
    },
    reducers:{
        // 有多个少个reducer函数，就有多少个对应的action
        // add=====>{type:"counter/add",payload:xxxx}
        add(state,action){
            // 1-不需要进行复制
            // 2-不需要进行返回
            state.num += action.payload;
        },
        jian(state,{payload}){
            state.num -= payload;
        }
    }
})

// 2- 生成store
const counter = counterSlice.reducer;
const store = configureStore({
    reducer:{
        counter
    }
})

// 3- 获取store中的状态（state)
//    store与state的关系：state = store.getState():
// const state = store.getState();
// console.log(state);// {counter:{num:0}}

// 4- 修改状态
//    可以通过store获取到dispatch
//        console.log(store.dispatch);
//    借助dispatch函数，可以指定action(行为）
//    action分为同步action(对象）,异步action（函数）
// 获取actions
// const actions = counterSlice.actions;
// console.log(actions);// {add:f,jian:f}
// console.log(actions.add(1));// {type: 'counter/add', payload: 1}
// console.log(actions.jian(2));// {type: 'counter/jian', payload: 2}

// 使用actions
const {add,jian} = counterSlice.actions;
// 以下代码会执行到counterSlice->reducers->add的方法，并为add传递当前的状态以及action
store.dispatch(add(1));// 相当于 store.dispatch({type:'counter/add',payload:1})
store.dispatch(add(1));// 相当于 store.dispatch({type:'counter/add',payload:1})
store.dispatch(add(1));// 相当于 store.dispatch({type:'counter/add',payload:1})
store.dispatch(add(1));// 相当于 store.dispatch({type:'counter/add',payload:1})
store.dispatch(jian(1));// 相当于 store.dispatch({type:'counter/jian',payload:1})
store.dispatch(jian(1));// 相当于 store.dispatch({type:'counter/jian',payload:1})
store.dispatch(jian(1));// 相当于 store.dispatch({type:'counter/jian',payload:1})
store.dispatch(jian(1));// 相当于 store.dispatch({type:'counter/jian',payload:1})
store.dispatch(jian(1));// 相当于 store.dispatch({type:'counter/jian',payload:1})
// store.dispatch({type:'counter/add',payload:1})
console.log(store.getState());





